<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="汇报人" prop="reportUserId">
        <el-select clearable  v-model="queryParams.reportUserId" filterable placeholder="选择汇报人" >
          <el-option
            v-for="user in filteredUsers"
            :key="user.userId"
            :label="user.nickName "
            :value="user.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['plan:plan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['plan:plan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['plan:plan:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['plan:plan:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-s-marketing"
          size="mini"
          @click="handleReport"
          v-hasPermi="['plan:plan:export']"
        >当月报表</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      border
      :data="planList"
      :span-method="arraySpanMethod"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <!-- 只显示合并后的序号 -->
          <span>
            {{ getMergedIndex(scope.row, scope.$index) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column  label="计划名称" align="center" prop="createTime" width="120">
        <template slot-scope="scope">
          {{ scope.row.extra1 }}
        </template>
      </el-table-column>
      <el-table-column  label="总采购量 (吨)" align="center" prop="purchaseQuantity">
        <template slot-scope="scope">
          {{ !scope.row.isClose ? scope.row.purchaseQuantity || 0 : '--' }}
        </template>
      </el-table-column>
      <el-table-column label="炼厂分配 (吨)" align="center" width="100">
        <template slot-scope="scope">
          <span
            :class="{
              'link-type': !scope.row.isClose,
              'underline': !scope.row.isClose
            }"
            @click="handleAddAllot(scope.row)"
          >
            {{ !scope.row.isClose ? `${refineryIdFormat(scope.row.refineryId)}：${scope.row.quantity || 0 }` : '--'  }}
          </span>
        </template>
      </el-table-column>
      <el-table-column  label="在途信息" align="center" width="240">
        <template slot-scope="scope">
          <span
            :class="{
              'link-type': transitFormat(scope.row),
            }"
            @click="handleUpdateAllot(scope.row)"
          >
            {{ transitFormat(scope.row) || '--' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column  label="物料状态" align="center" prop="status">
        <template slot-scope="scope">
          {{!scope.row.isClose ? statusFormat(scope.row.status) : '--'  }}
        </template>
      </el-table-column>
      <el-table-column label="本月已发 (吨)" align="center" >
        <template slot-scope="scope">
          {{!scope.row.isClose? scope.row.totalSendWeight.toFixed(3) || 0 : '--' }}
        </template>
      </el-table-column>
      <el-table-column  label="本月剩余 (吨)" align="center">
        <template slot-scope="scope">
          {{!scope.row.isClose? scope.row.totalSendWeight ? Number(( scope.row.quantity - scope.row.totalSendWeight).toFixed(3)) : scope.row.quantity : '--' }}
        </template>
      </el-table-column>

      <el-table-column label="异常情况" align="center" prop="error"  />
      <el-table-column label="汇报人" align="center" prop="reportUserId"  :formatter="reportPersonFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="110">
        <template slot-scope="scope">
          <template v-if="scope.row.noEdit">
            <!-- 收起 -->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-arrow-up"
              @click="handleExpand(scope.row)"
              v-if="!scope.row.isClose"
            >收起</el-button>
            <!-- 展开 -->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-arrow-down"
              @click="handleExpand(scope.row)"
              v-if="scope.row.isClose"
            >展开</el-button>
          </template>
          <template v-else>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['plan:plan:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['plan:plan:remove']"
            >删除</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" label-position="top" :model="form" :rules="rules">
        <el-row>
          <el-col :span="8">
        <el-form-item label="计划名称" prop="extra1" label-width="150px">
          <el-input disabled v-model="form.extra1" placeholder="请输入计划名称" style="width: 90%;" />
        </el-form-item>
        </el-col>
        <el-col :span="8">
        <el-form-item label="计划采购量(吨)" prop="purchaseQuantity" label-width="150px">
          <el-input  v-model="form.purchaseQuantity" placeholder="请输入计划名称" style="width: 90%;" />
        </el-form-item>
        </el-col>
        <el-col :span="8">
        <el-form-item label="汇报人" label-width="150px">
          <el-input readonly v-model="userName" placeholder="请输入计划名称" style="width: 90%;" />
        </el-form-item>
        </el-col>
        </el-row>
        <el-form-item label="异常情况" prop="error" label-width="150px">
          <el-input v-model="form.error" type="textarea" placeholder="请输入异常情况" />
        </el-form-item>
        <el-divider content-position="center">采购计划详情信息</el-divider>

        <el-table :data="reportPlanDetailList" :row-class-name="rowReportPlanDetailIndex" @selection-change="handleReportPlanDetailSelectionChange" ref="reportPlanDetail">
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="炼厂" prop="refineryName" width="150" align="center" />
          <el-table-column label="分配量" prop="quantity">
            <template slot-scope="scope">
              <el-input-number :min="0"  :precision='3' v-model="scope.row.quantity" placeholder="请输入分配量" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改在途油信息对话框 -->
    <el-dialog :title="titleAllot" :visible.sync="openAllot" width="680px" append-to-body>
      <el-form ref="formAllot" label-position="top" :model="formAllot" :rules="rules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="炼厂" prop="refineryId" >
              <el-select
                v-model="formAllot.refineryId"
                placeholder="请选择炼厂"
                style="width: 90%;"
                disabled
                class="is-readonly"
              >
                <el-option
                  v-for="item in filteredRefinerys"
                  :key="item.id"
                  :label="item.refineryName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="已发车数量 (车)" prop="sendCarCount">
              <el-input-number
                :min="1"
                :step="1"
                :precision="0"
                v-model="formAllot.sendCarCount"
                placeholder="请输入已发车数量"
                style="width: 90%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="已发量 (吨)" prop="sendWeight">
              <el-input-number
                :min="0"
                :precision='4'
                v-model="formAllot.sendWeight"
                placeholder="请输入已发量"
                style="width: 90%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出发时间" prop="startTime">
              <el-date-picker clearable size="small"
                v-model="formAllot.startTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择出发时间"
                style="width: 90%;"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计到达时间" prop="arriveTime">
              <el-date-picker clearable size="small"
                v-model="formAllot.arriveTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择预计到达时间"
                style="width: 95%;"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态"  prop="extra1">
              <el-select v-model="formAllot.extra1" filterable placeholder="选择状态" style="width: 90%;" >
                <el-option
                  v-for="user in filteredStatus"
                  :key="user.value"
                  :label="user.label"
                  :value="user.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上报用户"  prop="reportUserId">
              <el-input v-model="userName" readonly style="width: 95%;" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="异常情况" prop="error">
              <el-input v-model="formAllot.error" type="textarea" placeholder="请输入异常情况" style="width: 98%;" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormAllot">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfoPlan, getPlan, delPlan, addPlan, updatePlan, exportPlan, report } from '@/api/plan/plan'
import { getOnway, updateOnway, addOnway } from "@/api/onway/onway";
import { listUserNoPage } from '@/api/system/user'
import { listRefinery, listRefineryNoPage } from '@/api/report/refinery'
import { baseApiUrl } from '@/config/sysinfo'
export default {
  name: "Plan",
  data() {
    return {
      weightRule:false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedReportPlanDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购计划表格数据
      planList: [],
      // 采购计划详情表格数据
      reportPlanDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // id字典
      idOptions: [],
      // 计划采购量字典
      purchaseQuantityOptions: [],
      // 异常情况字典
      errorOptions: [],
      // 汇报人字典
      reportUserIdOptions: [],
      // 工作人字典
      workUserIdOptions: [],
      // 创建人字典
      createByOptions: [],
      // 创建时间字典
      createTimeOptions: [],
      // 修改人字典
      updateByOptions: [],
      // 修改时间字典
      updateTimeOptions: [],
      // 修改时间字典
      extra1Options: [],
      // 修改时间字典
      extra2Options: [],
      // 修改时间字典
      extra3Options: [],
      // 修改时间字典
      extra4Options: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        purchaseQuantity: null,
        reportUserId: null,
        workUserId: null,
      },
      filteredRefinerys:[],
      filteredUsers:[],
      // 表单参数
      form: {},
      planId: null,
      // 表单参数
      formAllot: {},
      // 表单校验
      rulesAllot: {
        planId: [
          { required: true, message: '采购计划不能为空', trigger: 'blur' }
        ],
        refineryId: [
          { required: true, message: '炼厂不能为空', trigger: 'blur' }
        ],
        sendCarCount: [
          { required: true, message: '已发车数量不能为空', trigger: 'blur' },
          { type: 'number', message: '必须为数字', trigger: 'blur' }
        ],
        sendWeight: [
          { required: true, message: '已发量不能为空', trigger: 'blur' },
          { type: 'number', message: '必须为数字', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '出发时间不能为空', trigger: 'blur' }
        ],
        arriveTime: [
          { required: true, message: '预计到达时间不能为空', trigger: 'blur' },
          { validator: this.validateArriveTime, trigger: 'blur' } // 添加自定义校验
        ],
        // arriveCarCount: [
        //   { required: true, message: '到库车数量不能为空', trigger: 'blur' },
        //   { type: 'number', message: '必须为数字', trigger: 'blur' }
        // ],
        arriveWeight: [
          // { required: true, message: '到库重量不能为空', trigger: 'blur' },
          { type: 'number', message: '必须为数字', trigger: 'blur' }
        ],
        extra1:[ { required: true, message: '状态不能为空', trigger: 'blur' }]
      },
      // 弹出层标题
      titleAllot: "",
      // 是否显示弹出层
      openAllot: false,
      // 表单校验
      rules: {
        extra1: [
          { required: true, message: "计划名称不能为空", trigger: "blur" }
        ],
        // purchaseQuantity: [
        //   { required: true, message: "计划采购量不能为空", trigger: "blur" }
        // ],
      },
      userName: this.$store.getters.name,
      userId: this.$store.getters.userId,
      filteredStatus:[{value:1,label:'未到站;未收油'},{value:2,label:'已到站;未收油'},{value:3,label:'已到站;已收油'},],
      initList: [],
    };
  },
  created() {
    this.getList();
    this.fetchRefinerys()
    this.fetchUsers()
    this.getDicts("${column.dictType}").then(response => {
      this.idOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.purchaseQuantityOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.errorOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.reportUserIdOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.workUserIdOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.createByOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.createTimeOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.updateByOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.updateTimeOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extra1Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extra2Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extra3Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extra4Options = response.data;
    });
  },
  watch: {
    // 深度监听整个 sendJson 数组
    'form.reportPlanDetailList': {
      handler(newVal) {
        // 如果 sendJson 为空或长度为 0，不处理
        if (!newVal || newVal.length === 0) {
          return;
        }

        const totalQuantity = this.form.reportPlanDetailList.reduce((total, item) => {
          return total + (parseFloat(item.quantity) || 0); // 处理可能为 NaN 的情况
        }, 0);
        // if (totalQuantity>this.form.purchaseQuantity){
        //   this.$message.error('各炼厂分配总额不得大于采购计划量');
        //   this.weightRule=true
        // }else {
        //   this.weightRule=false
        // }
      },
      deep: true // 深度监听
    },
    // 深度监听整个 sendJson 数组 用于计算总额
    'reportPlanDetailList': {
      handler(newVal) {
        if (!newVal || newVal.length === 0) {
          return;
        }

        this.form.purchaseQuantity = this.reportPlanDetailList.reduce((total, item) => {
          return total + (parseFloat(item.quantity) || 0); // 处理可能为 NaN 的情况
        }, 0);
      },
      deep: true // 深度监听
    }
  },
  methods: {
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      // 根据 row.extra1 相同的行进行合并 前5列和操作列
      if (
        columnIndex === 0 ||
        columnIndex === 1 ||
        columnIndex === 2 ||
        columnIndex === 3 ||
        columnIndex === 11
      ) {
        if (rowIndex > 0 && row.extra1 === this.planList[rowIndex - 1].extra1) {
          return [0, 0];
        }
        const count = this.planList.filter(item => item.extra1 === row.extra1).length;
        return [count, 1];
      }

      // 在row.extra1 相同的基础上 refineryId 相同的行进行合并
      if (columnIndex === 4 || columnIndex === 7 || columnIndex === 8) {
        if (
          rowIndex > 0 && row.extra1 === this.planList[rowIndex - 1].extra1 &&
          row.refineryId === this.planList[rowIndex - 1].refineryId
        ) {
          return [0, 0];
        }
        const count = this.planList.filter(item =>
          item.refineryId === row.refineryId && item.extra1 === row.extra1
        ).length;
        return [count, 1];
      }
      // 其他情况不合并
      return [1, 1];
    },
    shouldShowIndex(row, index) {
      if (index === 0) return true;
      return row.extra1 !== this.planList[index - 1].extra1 || row.refineryId !== this.planList[index - 1].refineryId;
    },
    getMergedIndex(row, index) {
      // 根据row.id 查询initList中的index
      const initIndex = this.initList.findIndex(item => item.id === row.id);
      if (initIndex === -1) return index + 1;
      return initIndex + 1;
    },
    changeQuantity(){
      const totalQuantity = this.form.reportPlanDetailList.reduce((total, item) => {
        return total + (parseFloat(item.quantity) || 0); // 处理可能为 NaN 的情况
      }, 0);
      // if (totalQuantity>this.form.purchaseQuantity){
      //   this.$message.error('各炼厂分配总额不得大于采购计划量');
      //   this.weightRule = true
      // }else {
      //   this.weightRule = false
      // }
    },
    handleReport(){
      window.open(process.env.VUE_APP_BASE_API + '/jmreport/view/1006421807828901888', '_blank');
    },
    reportPersonFormat(row, column) {
      const user = this.filteredUsers.find(user => user.userId === row.reportUserId);
      return user ? user.userName : '';
    },
    // 日期格式化函数
    formatDate(date) {
      const d = new Date(date);
      return `${d.getMonth() + 1}月${d.getDate()}号采购计划`;
    },
    calculateRate(row) {
      if (row.notSend !== 0) {
        row.rate = (row.send / row.notSend).toFixed(4);
      } else {
        row.rate = 0; // 或者根据业务需求处理除以0的情况
      }
    },
    fetchUsers() {
      this.loading=true;
      listUserNoPage().then(response => {
          this.filteredUsers = response.rows;
          this.loading = false;
        }
      );
    },
    fetchRefinerys() {
      this.loading=true;
      listRefineryNoPage().then(response => {
          this.filteredRefinerys = response.rows;

          this.filteredRefinerys.forEach(refinery => {
            let obj = {};
            obj.refineryId = refinery.id;
            obj.refineryName = refinery.refineryName;
            obj.quantity = 0
            this.reportPlanDetailList.push(obj);
          });
          this.loading = false;
        }
      );
    },
    /** 查询采购计划列表 */
    getList() {
      this.loading = true;
      report().then(response =>{
        console.log(response)
      })
      listInfoPlan(this.queryParams).then(response => {
        const list = [];
        const currentDate = new Date();
        const currentMonth = currentDate.getMonth() + 1;
        const currentYear = currentDate.getFullYear();
        const previousMonth = currentMonth === 1 ? 12 : currentMonth - 1;
        const previousMonthYear = currentMonth === 1 ? currentYear - 1 : currentYear;

        response.rows.forEach(item => {
          const itemDate = new Date(item.createTime);
          const itemMonth = itemDate.getMonth() + 1;
          const itemYear = itemDate.getFullYear();

          if (itemYear > previousMonthYear || (itemYear === previousMonthYear && itemMonth >= previousMonth)) {
            const flattened = this.flattenData(item);
            list.push(...flattened);
          } else {
            list.push({
              ...item,
              isClose: true,
              noEdit: true,
            });
          }
        });
        this.planList = list
        this.initList = JSON.parse(JSON.stringify(response.rows))
        this.total = response.total;
        this.loading = false;
      });
    },
    flattenData(row) {
      const flattened = [];
      row.detailInfos.forEach(detail => {
        // 计算每个 onway 的 sendWeight 的和 并添加到 flattened 数组中
        const totalSendWeight = detail.onways.reduce((total, onway) => total + (onway.sendWeight || 0), 0);
        detail.onways.forEach((onway, index) => {
          flattened.push({
            createTime: row.createTime,
            id: row.id,
            planId: row.id,
            extra1: row.extra1,
            purchaseQuantity: row.purchaseQuantity,
            reportUserId: row.reportUserId,
            detailId: detail.id,
            refineryId: detail.refineryId,
            quantity: detail.quantity,
            onwayId: onway.id,
            sendWeight: onway.sendWeight,
            startTime: onway.startTime,
            arriveTime: onway.arriveTime,
            sendCarCount: onway.sendCarCount,
            error: onway.error,
            status: onway.extra1,
            index: index + 1,
            totalSendWeight,
            noEdit: row.noEdit,
            isClose: row.isClose,
          });
        });

        if (detail.onways.length === 0) {
          flattened.push({
            createTime: row.createTime,
            id: row.id,
            planId: row.id,
            extra1: row.extra1,
            purchaseQuantity: row.purchaseQuantity,
            error: row.error,
            reportUserId: row.reportUserId,
            detailId: detail.id,
            refineryId: detail.refineryId,
            quantity: detail.quantity,
            onwayId: null,
            sendWeight: null,
            startTime: null,
            arriveTime: null,
            sendCarCount: null,
            status: null,
            totalSendWeight: 0,
            noEdit: row.noEdit,
            isClose: row.isClose,
          });
        }
      });
      return flattened;
    },
    handleExpand(row) {
      row.isClose = !row.isClose;
      // flattenData 处理当前行 进行展开或收起
      if (!row.isClose) {
        const flattened = this.flattenData(row);
        const index = this.planList.findIndex(item => item.id === row.id);
        this.planList.splice(index, 1, ...flattened);
      } else {
        const list = JSON.parse(JSON.stringify(this.initList));
        // 在原始数据中找到当前行的索引 并替换为当前行 删除全部展开的数据
        const index = list.findIndex(item => item.id === row.id);
        const number = this.planList.filter(item => item.id === row.id).length;
        const initRow = list[index];
        this.planList.splice(index, number, initRow);
      }
    },
    // id字典翻译
    idFormat(row, column) {
      return this.selectDictLabel(this.idOptions, row.id);
    },
    // 计划采购量字典翻译
    purchaseQuantityFormat(row, column) {
      return this.selectDictLabel(this.purchaseQuantityOptions, row.purchaseQuantity);
    },
    // 异常情况字典翻译
    errorFormat(row, column) {
      return this.selectDictLabel(this.errorOptions, row.error);
    },
    // filteredRefinerys字典翻译
    refineryIdFormat(refineryId, column) {
      const data = this.filteredRefinerys.find(refinery => refinery.id == refineryId);
      return data? data.refineryName : '';
    },
    // 工作人字典翻译
    workUserIdFormat(row, column) {
      return this.selectDictLabel(this.workUserIdOptions, row.workUserId);
    },
    // 创建人字典翻译
    createByFormat(row, column) {
      return this.selectDictLabel(this.createByOptions, row.createBy);
    },
    // 创建时间字典翻译
    createTimeFormat(row, column) {
      return this.selectDictLabel(this.createTimeOptions, row.createTime);
    },
    // 修改人字典翻译
    updateByFormat(row, column) {
      return this.selectDictLabel(this.updateByOptions, row.updateBy);
    },
    // 修改时间字典翻译
    updateTimeFormat(row, column) {
      return this.selectDictLabel(this.updateTimeOptions, row.updateTime);
    },
    // 修改时间字典翻译
    extra1Format(row, column) {
      return this.selectDictLabel(this.extra1Options, row.extra1);
    },
    // 修改时间字典翻译
    extra2Format(row, column) {
      return this.selectDictLabel(this.extra2Options, row.extra2);
    },
    // 修改时间字典翻译
    extra3Format(row, column) {
      return this.selectDictLabel(this.extra3Options, row.extra3);
    },
    // 修改时间字典翻译
    extra4Format(row, column) {
      return this.selectDictLabel(this.extra4Options, row.extra4);
    },
    statusFormat(extra1, column) {
      const user = this.filteredStatus.find(user => user.value+'' === extra1+'');
      return user ? user.label:'';
    },
    dateChange(data, format) {
      // 根据format 转换年月 或者年月日
      const date = new Date(data);
      if (format === 'yyyy年MM月') {
        return `${date.getFullYear()}年${date.getMonth() + 1}月`;
      } else if (format === 'yyyy年MM月dd日') {
        return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
      }
    },
    transitFormat(row, column) {
      return !row.isClose ?
        `${
          row.startTime ?
            '第' + row.index + '批次：' + this.dateChange(row.startTime, 'yyyy年MM月dd日') + '发油' + row.sendCarCount + '车,' + row.sendWeight + '吨；预计' + this.dateChange(row.arriveTime, 'yyyy年MM月dd日') + '时间到达' :
            ''
        }`: '--'
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openAllot = false;
      this.title = "添加采购计划";
      this.reset();
      this.resetAllot();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        purchaseQuantity: null,
        error: null,
        reportUserId: null,
        workUserId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        extra1: null,
        extra2: null,
        extra3: null,
        extra4: null
      };
      this.reportPlanDetailList = [];
      this.resetForm("form");
    },
    resetAllot() {
      this.formAllot = {};
      this.resetForm("formAllot");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.fetchRefinerys()
      this.open = true;
      this.title = "添加采购计划";
      // 获取当前日期
      const now = new Date();

      // 获取年份和月份
      const year = now.getFullYear();
      const month = now.getMonth() + 1; // getMonth() 返回值范围是 0-11，需加 1

      // 格式化月份，确保是两位数
      const formattedMonth = month < 10 ? `0${month}` : month;

      // 设置 form.name 的值
      this.form.extra1 = `${year}年${formattedMonth}月`;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPlan(id).then(response => {
        this.form = response.data;
        this.reportPlanDetailList = response.data.reportPlanDetailList;
        this.open = true;
        this.title = "修改采购计划";
      });
    },
    formatTrainingLevels(trainingLevels) {
      // 检查是否有值
      if (!trainingLevels) {
        // 如果没有值，返回提示信息
        return '暂无分配信息，点击分配';
      }
      // 将逗号转换为逗号加HTML换行标签
      return trainingLevels.replace(/。/g, ';<br>');
    },
    /** 提交按钮 */
    submitForm() {
      // if (this.weightRule){
      //   this.$message.error('各炼厂分配总额不得大于采购计划量');
      //   return
      // }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.reportPlanDetailList = this.reportPlanDetailList.filter(item => item.quantity > 0);
          this.form.reportUserId = this.userId;

          if (this.form.id != null) {
            updatePlan(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlan(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除采购计划编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPlan(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
	/** 采购计划详情序号 */
    rowReportPlanDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 采购计划详情添加按钮操作 */
    handleAddReportPlanDetail() {
      let obj = {};
      obj.extra1 = "";
      obj.extra2 = "";
      obj.extra3 = "";
      obj.extra4 = "";
      obj.onWay = "";
      obj.send = "";
      obj.notSend = "";
      obj.rate = "";
      obj.refineryId = "";
      obj.quantity = "";
      this.reportPlanDetailList.push(obj);
    },
    /** 采购计划详情删除按钮操作 */
    handleDeleteReportPlanDetail() {
      if (this.checkedReportPlanDetail.length == 0) {
        this.$alert("请先选择要删除的采购计划详情数据", "提示", { confirmButtonText: "确定", });
      } else {
        this.reportPlanDetailList.splice(this.checkedReportPlanDetail[0].index - 1, 1);
      }
    },
    /** 单选框选中数据 */
    handleReportPlanDetailSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.reportPlanDetail.clearSelection();
        this.$refs.reportPlanDetail.toggleRowSelection(selection.pop());
      } else {
        this.checkedReportPlanDetail = selection;
      }
    },
    /** 导出按钮操作 */
    handleExport() {

      this.download('plan/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)


      // const queryParams = this.queryParams;
      // this.$confirm('是否确认导出所有采购计划数据项?', "警告", {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning"
      //   }).then(() => {
      //     this.exportLoading = true;
      //     return exportPlan(queryParams);
      //   }).then(response => {
      //     this.download(response.msg);
      //     this.exportLoading = false;
      //   }).catch(() => {});
    },
    handleUpdateAllot(row) {
      getOnway(row.onwayId).then(response => {
        this.formAllot = response.data;
        this.openAllot = true;
        this.titleAllot = "修改在途油信息";
      });
    },
    handleAddAllot(row) {
      this.resetAllot();
      console.log("handleAddAllot")
      this.formAllot.planId = row.planId
      this.formAllot.refineryId = row.refineryId
      this.openAllot = true;
      this.titleAllot = "添加在途油信息";
    },
    submitFormAllot() {
      this.$refs["formAllot"].validate(valid => {
        if (valid) {
          this.formAllot.reportUserId = this.userId;

          if (this.formAllot.id != null) {
            updateOnway(this.formAllot).then(response => {
              this.msgSuccess("修改成功");
              this.openAllot = false;
              this.getList();
            });
          } else {
            addOnway(this.formAllot).then(response => {
              this.msgSuccess("新增成功");
              this.openAllot = false;
              this.getList();
            });
          }
        }
      });
    },
  }
};
</script>
